/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/**
 * 处理企业微信意见反馈
 *  */
import React, { useEffect, useRef, useState } from 'react';
import { Descriptions, Space, Row, Col, Image, message, Button } from 'antd';
import ProList from '@ant-design/pro-list';
import { PageContainer } from '@ant-design/pro-layout';
import { getFeedbackList, saveFeedback, ignoreFeedback } from '@/services/feedback';
import { debounce, random } from 'lodash';
import type { ActionType } from '@ant-design/pro-table';
import type { ListItem } from './types';
import styles from './index.less';
import config from './config.jsx';

const wxNumber = ['kuaibao168', 'kuaibao66', 'kuaibao77', 'kuaibao99'];

const HandleFeedback: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [source, setSource] = useState<string>('1');
  const [mobile, setMobile] = useState<string | null>('');
  const [name, setName] = useState<string | null>('');

  useEffect(() => {
    const params = window.location.search.split('?')[1];
    const searchParams = new URLSearchParams(params);
    const platform = searchParams.get('platform') || 'kdy';
    const platformMap = { kdy: '1', wzg: '2' };
    // 1 快递员 2 微掌柜
    setSource(platformMap[platform]);
    window.document.title = config.title[platform];
    setMobile(searchParams.get('courier_id') || '');
    setName(decodeURIComponent(searchParams.get('name') || ''));
  }, []);

  const onSubmit = async (_: any, row: ListItem) => {
    const { reply, id } = row;
    const res = await saveFeedback({
      id,
      reply,
      status: 1,
    });
    const { code, msg } = res;
    if (code == 0) {
      actionRef.current?.reload();
    } else {
      actionRef.current?.reload();
      message.error(msg);
    }
    return res;
  };

  const ignore = debounce(
    async (row: ListItem) => {
      const { id } = row;
      const wx = wxNumber[random(3, false)];
      const res = await ignoreFeedback({
        id,
        reply: `亲，您的问题描述的不够清晰，客服无法解答，如有疑问请加客服微信：${wx}`,
        status: 1,
      });
      const { code, msg } = res;
      if (code == 0) {
        actionRef.current?.reload();
      } else {
        actionRef.current?.reload();
        message.error(msg);
      }
    },
    500,
    {
      leading: true,
      trailing: false,
    },
  );

  return (
    <PageContainer
      className={styles.main}
      title='反馈意见处理'
      content={
        <Descriptions>
          <Descriptions.Item label='意见反馈人'>{name || mobile}</Descriptions.Item>
        </Descriptions>
      }
    >
      <ProList<ListItem>
        actionRef={actionRef}
        rowKey='id'
        pagination={{
          pageSize: 20,
          showSizeChanger: false,
        }}
        itemLayout='vertical'
        split
        showActions='always'
        request={async (params) => {
          const { current, pageSize } = params;
          return getFeedbackList({ page: current, pageSize, courier_id: mobile, source });
        }}
        editable={{
          onSave: onSubmit,
          actionRender: (_, __, defaultDom) => [
            <Button key='save' type='primary'>
              {defaultDom.save}
            </Button>,
            <Button key='cancel'>{defaultDom.cancel}</Button>,
          ],
        }}
        metas={{
          title: {
            dataIndex: 'phone',
            editable: false,
            render: (text) => <div style={{ marginRight: 20 }}>联系人：{text}</div>,
          },
          extra: {
            dataIndex: 'app',
            editable: false,
            render: (text, row) => (
              <Space size={50}>
                <Row align='middle' gutter={[10, 0]}>
                  {row.images.map((v) => (
                    <Col key={v}>
                      <Image src={v} width={40} height={40} />
                    </Col>
                  ))}
                </Row>
                <div>{text}</div>
                <div>{row.create_at}</div>
              </Space>
            ),
          },
          content: {
            dataIndex: 'reply',
            valueType: 'textarea',
            render: (text, row) => {
              if (text === '-') {
                return null;
              }
              return (
                <Row>
                  <Col>{row.reply_user}：</Col>
                  <Col>{text}</Col>
                </Row>
              );
            },
          },
          description: {
            valueType: 'textarea',
            dataIndex: 'content',
            editable: false,
          },
          actions: {
            render: (text, row, index, action) => (
              <Row gutter={[20, 20]}>
                {row.status == '0' && (
                  <>
                    <Col>
                      <Button
                        type='primary'
                        onClick={() => {
                          action?.startEditable(row.id);
                        }}
                        key='link'
                      >
                        回复
                      </Button>
                    </Col>
                    <Col>
                      <Button onClick={() => ignore(row)} key='link'>
                        忽略
                      </Button>
                    </Col>
                  </>
                )}
              </Row>
            ),
          },
        }}
      />
    </PageContainer>
  );
};

export default React.memo(HandleFeedback);
